import json
from datetime import datetime
from app.extensions import redis
from app.models.message import Message
from app.ws.connection import connection_manager

USER_MESSAGE_CHANNEL = 'user_message:{}'
GROUP_MESSAGE_CHANNEL = 'group_message:{}'
USER_STATUS_CHANNEL = 'user_status'

def publish_message(message_id):
    """发布消息到Redis频道"""
    message = Message.query.get(message_id)
    if not message:
        return
    
    message_data = {
        'id': message.id,
        'type': 'message',
        'sender_id': message.sender_id,
        'receiver_id': message.receiver_id,
        'content': message.content,
        'message_type': message.message_type,
        'is_group': message.is_group,
        'status': message.status,
        'created_at': message.created_at.isoformat()
    }
    
    if message.is_group:
        channel = GROUP_MESSAGE_CHANNEL.format(message.receiver_id)
    else:
        channel = USER_MESSAGE_CHANNEL.format(message.receiver_id)
    
    # 发布消息
    redis.publish(channel, json.dumps(message_data))
    
    # 如果是私聊消息，还需要发送给发送者一份（用于多设备同步）
    if not message.is_group:
        sender_channel = USER_MESSAGE_CHANNEL.format(message.sender_id)
        redis.publish(sender_channel, json.dumps(message_data))

def listen_for_messages(user_id):
    """监听用户的消息频道"""
    pubsub = redis.pubsub()
    pubsub.subscribe(
        USER_MESSAGE_CHANNEL.format(user_id),
        USER_STATUS_CHANNEL
    )
    
    for message in pubsub.listen():
        if message['type'] == 'message':
            yield message['data']

def listen_for_group_messages(group_id):
    """监听群组的消息频道"""
    pubsub = redis.pubsub()
    pubsub.subscribe(GROUP_MESSAGE_CHANNEL.format(group_id))
    
    for message in pubsub.listen():
        if message['type'] == 'message':
            yield message['data']